package question.solution50;

import question.SolutionTemplate;
import sun.security.jgss.spnego.SpNegoMechFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Solution50 implements SolutionTemplate {

    public double myPow(double x, int n) {
        long m = n;
        boolean negative = false;
        if(m < 0){
            negative = true;
        }else if(m == 0){
            return 1;
        }
        m = Math.abs(m);
        boolean[] powers = new boolean[32];
        for (int i = 0; i < 32; i++) {
            if((m & (1<<i)) >0){
                powers[i] = true;
            }
        }
        Map<Integer, Double> pvMap = getPV(powers, x);
        double result = 1;
        for(int i = 0; i < 32; i++){
            if(powers[i]){
                result*=pvMap.get(i);
            }
        }
        if(negative){
            return 1/result;
        }
        return result;
    }
    private Map<Integer, Double> getPV(boolean[] powers, double x){
        int i = -1;
        for (i = 31; i >=0 ; i--) {
            if(powers[i]){
                break;
            }
        }
        double p = x;
        Map<Integer, Double> pvMap = new HashMap<> ();
        pvMap.put(0, p);
        for (int j = 1; j <= i; j++) {
            p = p*p;
            pvMap.put(j, p);
        }
        return pvMap;
    }

//    private

    @Override
    public void test() {
        double result = myPow(2,-2);
        System.out.println();
        return;
    }
}
